package com.amazon.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.amazon.shop.bean.dto.BatchExportForm;
import com.amazon.shop.bean.dto.EvaluateDTO;
import com.amazon.shop.bean.entity.Evalform;
import com.amazon.shop.bean.entity.Priduct;
import com.amazon.shop.bean.entity.Store;
import com.amazon.shop.bean.enums.ResultEnum;
import com.amazon.shop.bean.vo.Ret;
import com.amazon.shop.cache.LocalCache;
import com.amazon.shop.exception.BusinessException;
import com.amazon.shop.mapper.EvalformMapper;
import com.amazon.shop.mapper.PriductMapper;
import com.amazon.shop.mapper.StoreMapper;
import com.amazon.shop.service.IEvalformService;
import com.amazon.shop.util.ChinaIPRecognizer;
import com.amazon.shop.util.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzj
 * @since 2021-01-25
 */
@Service
public class EvalformServiceImpl extends ServiceImpl<EvalformMapper, Evalform> implements IEvalformService {

    private static boolean ipflag = true;

    @Resource
    private PriductMapper priductMapper;

    @Resource
    private StoreMapper storeMapper;

    @Override
    public Ret chengeIpFlag(Integer ipFlag){
        if (ipFlag==1) {
            ipflag = true;
        }else if (ipFlag == 0){
            ipflag = false;
        }
        return ResultUtil.success();
    }

    @Override
    public Ret getChengeIpFlag() {
        return ResultUtil.success(ipflag);
    }

    @Override
    @Transactional
    public Ret subEvaluate(EvaluateDTO evaluated) {
        if(ipflag){
            //中国ip拦截
            String ip = evaluated.getIp();
            if (ChinaIPRecognizer.isCNIP(ip)) {
                throw new BusinessException(ResultEnum.IPINTERCEPT);
            }
        }

        String redeemcode = evaluated.getRcode();
        String mid = evaluated.getMid();
        Integer storeid = null;
        if(StrUtil.isNotEmpty(mid)){
            //校验店铺是否存在
            Map<String, Object> columnMap = MapUtil.newHashMap();
            columnMap.put("mid", mid);
            List<Store> stores = storeMapper.selectByMap(columnMap);
            if (stores!=null&&stores.size() > 0) {
                Store store = stores.get(0);
                storeid = store.getId();
            }else {
                throw new BusinessException(ResultEnum.STOREEERROR);
            }
        }
//        else {
//            throw new BusinessException(ResultEnum.STOREEERROR);
//        }
        //校验兑换码是否存在
        QueryWrapper<Priduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rcode",redeemcode);
        if(storeid!=null){
            queryWrapper.eq("storeid",storeid);
        }
        queryWrapper.select("storeid","purl");
        Priduct priduct = priductMapper.selectOne(queryWrapper);
        if(priduct ==null|| priduct.getStoreid()==null){
            throw new BusinessException(ResultEnum.SUBEVALUATEERROR1);
        }
        //校验是否已添加
        Evalform evalform = new Evalform();
        BeanUtil.copyProperties(evaluated, evalform);
        evalform.setStoreid(priduct.getStoreid());
        QueryWrapper<Evalform> tblEformQWrapper = new QueryWrapper<>();
        tblEformQWrapper.eq("orderid",evaluated.getOrderid());
        tblEformQWrapper.select("id");
        Evalform rettblEvalform = this.getOne(tblEformQWrapper);
        if (rettblEvalform != null) {
            throw new BusinessException(ResultEnum.SUBEVALUATEERROR2);
        }
        //插入数据
        this.save(evalform);
        return ResultUtil.success(priduct.getPurl());
    }

    @Override
    public void batchExport(HttpServletResponse response, BatchExportForm batchExportForm){
        Integer storeid = batchExportForm.getStoreid();
        Integer satisfied = batchExportForm.getSatisfied();
        Long stime = batchExportForm.getStime();
        Long etime = batchExportForm.getEtime();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("storeid","subname","evalemail","orderid","country","rcode","satisfied","issend","createtime","refundamount","sku","disc","remark");
        if (storeid != null) {
            queryWrapper.eq("storeid", storeid);
        }
        if (satisfied != null) {
            queryWrapper.eq("satisfied", storeid);
        }
        queryWrapper.ge("createtime",new Date(stime));
        queryWrapper.lt("createtime",new Date(etime));
        ServletOutputStream out = null;
        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        if (list.size() == 0) {
            PrintWriter outhtml = null;
            try {
                //生成html页面代码
                String html = "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "  <meta charset=\"UTF-8\">\n" +
                        "  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                        "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                        "  <title>无可导出数据</title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "\t<center><h4>无可导出数据</h4></center>\n" +
                        "</body>\n" +
                        "</html>";
                response.setContentType("text/html;charset=utf-8");
                outhtml = response.getWriter();
                outhtml.println(html);
                return;
            } catch (IOException e) {
                throw new BusinessException(ResultEnum.FAILURE);
            }finally {
                if(outhtml!=null) {
                    outhtml.close();
                }
            }
        }
        for (Map<String, Object> map : list) {
            Integer sid = (Integer) map.get("storeid");
            String storename = (String) LocalCache.storenameCache.get(sid);
            map.put("storename",storename);
            Date time = (Date) map.get("createtime");
            String format = DateUtil.format(time, "yyyy-MM-dd HH:mm:ss");
            map.put("createtime",format);
            map.remove("storeid");

            Integer sfied = (Integer)map.get("satisfied");
            map.put("satisfied",sfied==0?"不满意":"满意");

            Integer issend = (Integer)map.get("issend");
            map.put("issend",issend==0?"未发送":"已发送");


            if (map.get("refundamount")==null) {
                map.put("refundamount","");
            }
            if (map.get("sku")==null) {
                map.put("sku","");
            }
            if (map.get("disc")==null) {
                map.put("disc","");
            }
            if (map.get("remark")==null) {
                map.put("remark","");
            }
        }
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.setColumnWidth(0,30);
        writer.addHeaderAlias("storename","店铺名");

        writer.setColumnWidth(1,30);
        writer.addHeaderAlias("subname","评论人昵称");

        writer.setColumnWidth(2,30);
        writer.addHeaderAlias("orderid","订单id");

        writer.setColumnWidth(3,30);
        writer.addHeaderAlias("evalemail","评论人邮箱地址");

        writer.setColumnWidth(4,30);
        writer.addHeaderAlias("country","国家");

        writer.addHeaderAlias("rcode","兑换码");

        writer.addHeaderAlias("satisfied","是否满意");

        writer.addHeaderAlias("issend","是否已发送邮件");

        StyleSet style = writer.getStyleSet();
        CellStyle cellStyleForDate = style.getCellStyleForDate();
        writer.setColumnWidth(8,cellStyleForDate.getDataFormat());
        writer.addHeaderAlias("createtime","评价时间");

        writer.addHeaderAlias("refundamount","返款金额");

        writer.addHeaderAlias("sku","产品SKU");

        writer.addHeaderAlias("disc","折扣码");

        writer.addHeaderAlias("remark","备注");





        //合并单元格后的标题行，使用默认标题样式
        int lastcolumn =  list.get(0).entrySet().size()-1;
        writer.merge(lastcolumn, "评价列表信息");
        writer.write(list,true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
            IoUtil.close(out);
        }
    }
}
